//加载各个模块得内容
define(function(require, exports, module) {
	let configAll = "";
	let theme = "";
	config = "";
	let yizhu = {};
	var loadlist = {};
	var baseurl= common.getRootPath()
	/* 所有的模块的临时容器 */
	let moduleTemp = [];
	loaduserData(function(datas) {
		// $("body").append(
		// 	'<iframe id="loadingjiazai" widgetId="loadingjiazai" src="'+commonbasePath+'/common/base/load/loading.html" style="position: absolute;border: 0;z-index: 99999999999;"  width="100%" height="100%"></iframe>'
		// )
		if (datas.code == 200) {
			window.userInfo = datas.user
			configAll = datas.configAll;
			config = configAll.config;
			if (datas.baseUrl) {
				baseurls(datas.baseUrl);
			}
			/* 主题 */
			theme = config.theme.name[0];
			// theme = "LaunchpadTheme_dark_top";
		}
	});
	//根据widget.uri获取 widget的配置信息
	pubsub.subscribe("system_getWidgetMsg", function(topic, data) {
		return getWidgetMsg(data, configAll.allWidget)
	})
	//widget 生命周期
	pubsub.subscribe("system_widgetTheLateNotice", function(topic, data) {
		widgetTheLateNotice(data)
	})
	/* widget加载器 */
	pubsub.subscribe("system_loadWidgetPool", function(topic, data) {
		loadWidgetPool(data);
	})
	/* 弹出单独网页 */
	pubsub.subscribe("system_widget_window_open", function(topic, data) {
		// let tar = common.GetQueryString("name")
		window.open(common.getRootPath() + "/index.html?"+ jQuery.param(data));
	})
	/* drawer缓存 */
	pubsub.subscribe("system_widget_layer_drawer", function(topic, data) {
		let widget = getWidgetMsg(data.data.widget, configAll.allWidget);
		// $("#"+(widget.uri+"drawer")).remove();
		if (!widget) {
			alert("没有找到" + data.data.widget + "组件的配置信息，您没有权限访问这个组件？")
		}
		// if(!drawerList[widget.uri]){
		var tar =
			'<el-drawer id="' + (widget.uri + "drawer") +
			'" v-if="drawer" :title="title" 	 :visible.sync="drawer" :direction="direction" append-to-body="true" close-on-press-escape :size="size" >' +
			'<iframe width="100%" height="100%" scrolling="auto" frameborder="0" src="' + common
			.getRootPath() + "/index.html?" +
			jQuery.param(data.data) + '"></iframe>' +
			'</el-drawer>'
		$("body").append(tar)
		var mainDiv = new Vue({
			el: "#" + (widget.uri + "drawer"),
			data() {
				return {
					drawer: true,
					direction: data.layer.direction ? data.layer.direction : "rtl",
					title: data.layer.title ? data.layer.title : widget.title,
					size: data.layer ? data.layer.size : "70%"
					// destroydrawer: true
				};

			},
			created() {
				this.initData()
			},
			mounted() {},
			methods: {
				initData() {
					console.log(this.tardata)
				},
			},

		})
		// 	drawerList[widget.uri]=mainDiv;
		// }else{
		// 	drawerList[widget.uri].$data.drawer=true;
		// }


	})
	
	/* 子组件唤醒 */
	// pubsub.subscribe("system_widget_layer_drawer", function(topic, data) {
	// 	var tar =
	// 		'<el-drawer id="' + (widget.uri + "drawer") +
	// 		'" v-if="drawer" :title="title" 	 :visible.sync="drawer" :direction="direction" append-to-body="true" close-on-press-escape :size="size" >' +
	// 		'<iframe width="100%" height="100%" scrolling="auto" frameborder="0" src="' + common
	// 		.getRootPath() + "/index.html?" +
	// 		jQuery.param(data.data) + '"></iframe>' +
	// 		'</el-drawer>'
	// 	$("body").append(tar)
	// 	var mainDiv = new Vue({
	// 		el: "#" + (widget.uri + "drawer"),
	// 		data() {
	// 			return {
	// 				drawer: true,
	// 				direction: data.layer.direction ? data.layer.direction : "rtl",
	// 				title: data.layer.title ? data.layer.title : widget.title,
	// 				size: data.layer ? data.layer.size : "70%"
	// 				// destroydrawer: true
	// 			};
	
	// 		},
	// 		created() {
	// 			this.initData()
	// 		},
	// 		mounted() {},
	// 		methods: {
	// 			initData() {
	// 				console.log(this.tardata)
	// 			},
	// 		},
	
	// 	})
	
	// })

	/* 系统内部弹窗 */
	pubsub.subscribe("system_widget_layer_open", function(topic, data) {

		let widget = getWidgetMsg(data.data.widget, configAll.allWidget)
		if (!widget) {
			alert("没有找到" + data.data.widget + "组件的配置信息，您没有权限访问这个组件？")
		}
		var defultOpen = {
			type: 2,
			anim: 5,
			shade: 0,
			// title:'<span class="iconfont '+widget.button.img+'" style="color: '+widget.button.color+';"></span>'+(widget?widget.title:data.layer.title),
			title: widget ? widget.title : data.layer.title,
			area: ['80%', '80%'],
			shade: [0.5, '#000'],
			shadeClose: true,
			maxmin: true,
			skin: 'class_common',
			content: common.getRootPath() + "/index.html?" + jQuery.param(data.data),
			min: function(layero, index) {
				// return false;
			},
			success: function(layero, index) {
				// $(layero).find(".layui-layer-title").html('<span class="iconfont '+widget.button.img+'" style="background-color: '+widget.button.color+'">'+(widget?widget.title:data.layer.title)+'</span>')
				// debugger
			}
		};
		if (!data.layer) {
			data.layer = {};
		}
		var tar = $.extend(defultOpen, data.layer)
		var inde = layer.open(tar);
		return inde;


	})

	/*加载两侧面板 */
	function loadWidgetPool(data) {
		if (data.layer && data.layer.show) {
			pubsub.publish("task_createBtn_Botton", data)
		}
		/* 如果存在直接显示 */
		if (data.layer && $("#" + data.layer.id).length === 1) {

		} else {
			/* 开始加载 */
			loadWidgetMoudel(widgetsPathGroup({
				uri: data.uri,
				base: data.uri
			}))
		}
	};
	/* 组装config */
	function loadAllPanel() {
		if (config.leftPanel.length > 0) {
			pubsub.publish("layout_createPanelBtn", configAll.widgetChid);
			var widgets = configAll.allWidget;
			for (const widget of widgets) {
				/* 不存在弹出层 */
				if (!widget.layer) {
					loadWidgetPool(widget);
				} else {
					// 面板默认显示 ，就加载模块
					if (widget.layer.loading) {
						loadWidgetPool(widget)
					}
				}
			}
		}
	};

	function baseurls(datas) {
		var tar = {}
		for (const element of datas) {
			tar[element.key] = element.value
		}
		alluse = $.extend(tar, alluse);
	}
	/* 初始化vue对象 */
	function initVue(data, tar) {
		if (data) {
			data.el = "#" + tar;
			new Vue(data)
		}
	}

	function getWidgetMsg(widget, allWid) {
		var tar;
		for (const element of allWid) {
			if (element.uri == widget) {
				tar = element;
				break;
			}
		}

		return tar;
	}

	function createWidgetHtml(widgetn, data) {
		var tar = $('<div class="' + widgetn.uri + '" ><div id = "' + widgetn.uri + '">' + data.html +
			'</div></div>')
		if (widgetn.show) {
			$("." + theme + " .mid-content").append(tar);
		} else {
			$("." + theme + " .mid-content").append(tar.hide());

		}
	};

	function findParent(data, widget, html) {
		console.log("%c" + data.url + '组装成功', "color:" + "#008000");

		/* 路径分割 */
		var data1Array = data.url.split("/html/");
		/* 目标位置 */
		var tar = data1Array[data1Array.length - 1];
		/* 分割长度 */
		var data1ArrayLength = data1Array.length;
		/* 主题走的逻辑 */
		if (data1ArrayLength == 1 && data.type == "theme") {
			$("body").append($(html).addClass(theme).attr("id", theme).attr("widgetId", theme));
			yizhu[data1Array[0]] = widget;
			/* widgets没有子组件走的逻辑 */
		} else if (data1ArrayLength == 1 && data.parent == undefined) {
			yizhu[tar] = widget;
			yizhu[tar].template = html
		} else if (data1ArrayLength == 1) {
			yizhu[tar] = widget;
			yizhu[tar].template = html
		} else if (data1ArrayLength == 2) {
			yizhu[data1Array[0]].components[tar] = widget;
			yizhu[data1Array[0]].components[tar].template = html

		} else if (data1ArrayLength == 3) {
			yizhu[data1Array[0]].components[data1Array[1]].components[tar] = widget;
			yizhu[data1Array[0]].components[data1Array[1]].components[tar].template = html;

		} else if (data1ArrayLength == 3) {
			yizhu[data1Array[0]].components[data1Array[1]].components[data1Array[2]].components[tar] = widget;
			yizhu[data1Array[0]].components[data1Array[1]].components[data1Array[2]].components.template = html;

		}

	}

	function addmoudel(data, widget, html, tar) {
		data.components[tar] = widget
		data.components[tar].template = html
	}
	/* 模块加载器 */
	function loadWidgetMoudel(data) {
		/* 根节点 */
		var tarjj = getUrl(data)
		if (data.parent == undefined) {
			loadlist[data.url] = []
		} else {
			loadlist[data.url.substring(0, data.url.indexOf("/"))].push(data.url)
		}
		const p = new Promise((resolve, reject) => {
			moduleTemp.push(data.url);
			try {
				require.async(data.data, function(css, widget, html, config) {
					resolve({
						widget: widget,
						html: html,
						config: config
					})
				})
			} catch (e) {
				//TODO handle the exception
			}
		})
		p.then(res => {
			res.widget.base = data.base
			/* 获取widget对象 */
			var parentWidgetJs = res.widget.onload(res.config, res.widget.base);
			/* 组装想要的vue的对象 */
			findParent(data, parentWidgetJs, res.html);
			if (parentWidgetJs.components && parentWidgetJs.components.length > 0) {
				var tempcom = {}
				for (var j = 0; j < parentWidgetJs.components.length; j++) {
					tempcom[parentWidgetJs.components[j]] = parentWidgetJs.components[j]
				}
				parentWidgetJs.components = tempcom;
				parentWidgetJs.base = res.widget.base;
				for (const element in parentWidgetJs.components) {
					const baseTar = data.url + "/html/" + element;
					if (data.type == "theme") {
						var temp = widgetsPathGroup({
							uri: baseTar,
							base: element,
							css: "css"
						}, true);
					} else {
						var temp = widgetsPathGroup({
							uri: baseTar
						});
					}
					temp.parent = data.base
					if (temp.url.indexOf("/") != -1) {
						let tt = temp.url.split("/")
						temp.base = tt[tt.length - 1]
					}
					// console.log(temp.base)
					loadlist[tarjj].remove(data.url)
					removeLoading(data.url)
					loadWidgetMoudel(temp);
				}
				/* 如果没有孩子节点的直接走下面这个 */
			} else {
				loadlist[tarjj].remove(data.url)

				/* 主题初始化完毕并加载了子组件*/
				if (loadlist[tarjj].length == 0 && tarjj == theme) {
					initVue(yizhu[tarjj], tarjj)
					loadAllPanel();
				} else if (loadlist[tarjj].length == 0) {
					/* 这一块有问题 */
					const widgetn = getWidgetMsg(tarjj, configAll.allWidget);
					if (!widgetn.layer && widgetn.loading) {
						createWidgetHtml(widgetn, {
							html: yizhu[tarjj].template
						});
						initVue(yizhu[tarjj], tarjj)
					} else {
						/* 最后一个参数要的是页面的元素 */
						pubsub.publish("system_widgetlayer", {
							widgetn: widgetn,
							data: {
								html: yizhu[tarjj].template
							}
						})
						delete yizhu[tarjj].template;
						initVue(yizhu[tarjj], tarjj)
					}
				}
				removeLoading(data.url)
			}

			// console.log(yizhu)
			// console.log(loadlist)

		})
	};
	/* 获取url的根节点 */
	function getUrl(data) {
		if (data.url.indexOf("/") == -1) {
			var tarjj = data.url
		} else {
			var tarjj = data.url.substring(0, data.url.indexOf("/"))
		}
		return tarjj;
	}
	/* 移除正在加载 */
	function removeLoading(data) {
		moduleTemp.remove(data);
		if (moduleTemp.length == 0&&data!=theme) {
			$("#loadingjiazai").remove();
		}
	}

	function widgetTheLateNotice(res, tar) {
		if (res.widget[tar]) {
			res.widget[tar](res.config)
		}
	}

	function systemStart() {
		loadWidgetMoudel(widgetsPathGroup({
			uri: theme,
			base: theme,
			show: true
		}, true))
	}
	/* 获取用户信息 */
	function loaduserData(callback) {
		$.ajax({
			type: "GET",
			async: false,
			url: alluse.bigcenter + "/getInfo",
			dataType: "json",
			success: function(data, status, xhr) {
				callback(data)
			},
			error: function(e) {
				alert("别看了链接后台出错了")
			}

		});
	}
	/* 组装widgets请求路径 */
	function widgetsPathGroup(tar, flg) {
		var type = ""
		if (flg) {
			type = "theme"
			var csstt = tar.css ? tar.css : config.theme.styles[0]
			var cssFile = baseurl + "/theme/" + tar.uri + "/" + csstt + "/style.css";
			var jsFile = baseurl + "/theme/" + tar.uri + "/Widget.js";
			var htmlFile = baseurl + "/theme/" + tar.uri + "/Widget.html";
			var configFile = baseurl + "/theme/" + tar.uri + "/config.json";
		} else {
			var cssFile = baseurl + "/widgets/" + tar.uri + "/css/style.css";
			var jsFile = baseurl + "/widgets/" + tar.uri + "/Widget.js";
			var htmlFile = baseurl + "/widgets/" + tar.uri + "/Widget.html";
			var configFile = baseurl + "/widgets/" + tar.uri + "/config.json";
			type = "widgets"

		}
		return {
			data: [cssFile, jsFile, htmlFile, configFile],
			base: tar.base,
			url: tar.uri,
			type: type
		};
	}
	module.exports = {
		start: systemStart
	};
})